package service

import (
	"errors"
	"go-admin/define"
	"go-admin/helper"
	"go-admin/models"
	"net/http"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

// LoginPassword 用户登录
func LoginPassword(c *gin.Context) {
	in := new(LoginPasswordRequest)
	err := c.ShouldBindJSON(in)

	if err != nil {
		// c.JSON(http.StatusOK, gin.H{
		// 	"code": -1,
		// 	"msg":  err.Error(),
		// })
		c.JSON(http.StatusOK, define.ErrorResult(err.Error()))
		return
	}

	//根据账号和密码查询用户
	sysUser, err := models.GetUserByUsernamePassword(in.UserName, in.Password)
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			// c.JSON(http.StatusOK, gin.H{
			// 	"code": -1,
			// 	"msg":  "用户名或密码错误",
			// })
			c.JSON(http.StatusOK, define.ErrorResult("用户名或密码错误"))
			return
		}
	}

	// fmt.Println("++++++++++++++++++++++++++++++++++++++++")
	// fmt.Println(sysUser.ID)
	// fmt.Println(sysUser.RoleId)
	// fmt.Println("++++++++++++++++++++++++++++++++++++++++")

	//生成token
	token, err := helper.GenerateToken(sysUser.ID, sysUser.RoleId, sysUser.UserName, define.TokenExpire)
	if err != nil {
		// c.JSON(http.StatusOK, gin.H{
		// 	"code": -1,
		// 	"msg":  err.Error(),
		// })
		c.JSON(http.StatusOK, define.ErrorResult(err.Error()))
		return
	}

	// 刷新token
	refreshToken, err := helper.GenerateToken(sysUser.ID, sysUser.RoleId, sysUser.UserName, define.RefreshTokenExpire)
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			// c.JSON(http.StatusOK, gin.H{
			// 	"code": -1,
			// 	"msg":  "用户名或密码错误",
			// })
			c.JSON(http.StatusOK, define.ErrorResult("用户名或密码错误"))
			return
		}
	}

	data := &LoginPasswordReply{
		Token:        token,
		RefreshToken: refreshToken,
	}

	c.JSON(http.StatusOK, gin.H{
		"code":     200,
		"msg":      "登录成功",
		"result":   data,
		"userInfo": sysUser,
	})

}
